/**
 * v-copy
 * 复制某个值至剪贴板
 * 接收参数：string类型/Ref<string>类型/Reactive<string>类型
 */
import type { Directive, DirectiveBinding } from 'vue'
import Dialog from '@/components/dialog/dialog'
interface ElType extends HTMLElement {
  copyData: object
  __handleClick__: any
  successMsg: string // 复制成功提示内容
}
export const copy: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    console.log('copy data', binding.value.data);
    el.copyData = binding.value.data
    el.successMsg = binding.value.msg
    // @ts-ignore
    el.addEventListener('click', handleClick)
  },
  updated(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value.data
  },
  beforeUnmount(el: ElType) {
    el.removeEventListener('click', el.__handleClick__)
  }
}

function handleClick(this: ElType) {
  const input = document.createElement('input')
  input.value = this.copyData.toLocaleString()
  document.body.appendChild(input)
  input.select()
  document.execCommand('Copy')
  document.body.removeChild(input)
  const msg = this.successMsg
  Dialog(msg)
}
